#region Using References

using System;
using System.Drawing;
using System.Threading.Tasks;
using System.Windows.Input;
using Beaker.OpenCube.Dynamic;
using Beaker.OpenCube.Textures;
using Beaker.OpenCube.WorldViewer.Messages;
using Beaker.Services.FileSystem;
using GalaSoft.MvvmLight.Command;

#endregion

namespace Beaker.OpenCube.WorldViewer.ViewModels
{
	public class OpenTexturePackViewModel
		: ViewModel
	{
		private readonly MainViewModel _owner;
		private readonly IFile _texturePackFile;

		public OpenTexturePackViewModel( MainViewModel owner, IFile file )
		{
			_owner = owner;
			_texturePackFile = file;
			_openTexturePackCommand = new RelayCommand( OpenTexturePack );

			GetTextureInfoAsync();
		}

		/// <summary>
		/// Gets the file of the texture pack
		/// </summary>
		public IFile File
		{
			get { return _texturePackFile; }
		}

		private string _texturePackName;

		/// <summary>
		/// Gets the name of this texture pack.
		/// </summary>
		/// <value>
		/// The name of this texture Pack.
		/// </value>
		public string Name
		{
			get { return _texturePackName; }
			private set { SetValue( ref _texturePackName, value, OnWorldNameChanged ); }
		}

		private void OnWorldNameChanged( string oldName, string newName )
		{
			RaisePropertyChanged( () => DisplayName );
		}

		/// <summary>
		/// Gets the display name.
		/// </summary>
		/// <value>
		/// The display name.
		/// </value>
		public string DisplayName
		{
			get
			{
				if( !string.IsNullOrEmpty( _texturePackName ) )
					return _texturePackFile.Name;

				return _texturePackName;
			}
		}

		private Image _image;

		/// <summary>
		/// Gets or sets the image.
		/// </summary>
		/// <value>
		/// The image.
		/// </value>
		public Image Image
		{
			get { return _image; }
			private set { SetValue( ref _image, value ); }
		}

		private async void GetTextureInfoAsync()
		{
			Tuple<Bitmap, string> info = await Task.Run( () =>
			{

				DynamicTexturePack texture = _owner.Game.OpenTexturePack( _texturePackFile );
				Tuple<Bitmap, string> tuple = Tuple.Create(
					texture.GetImage( "pack.png" ),
					texture.Name
				);

				return tuple;
			} );

			Image = info.Item1;
			Name = info.Item2;
		}

		private readonly RelayCommand _openTexturePackCommand;

		public ICommand OpenTexturePackCommand
		{
			get { return _openTexturePackCommand; }
		}

		private void OpenTexturePack()
		{
			ITexturePack texturePack = _owner.Game.OpenTexturePack( _texturePackFile );
			
			new ChangeTexturePackMessage( texturePack )
				.Send();
		}
	}
}